using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace MadLibrary.Text.EPub
{
    /// <summary>
    /// Represents a NavPoint in a NCX navigation map.
    /// </summary>
    public class NavPoint
    {
        /// <summary>
        /// Gets or sets the ID of the NavPoint
        /// </summary>
        public string ID { get; set; }

        /// <summary>
        /// Gets or sets the label of the NavPoint
        /// </summary>
        public string Label { get; set; }

        /// <summary>
        /// Gets or sets the ID of the source document the nav point points to.
        /// </summary>
        public string SrcID { get; set; }

        /// <summary>
        /// Gets or sets the PlayOrder of the NavPoint.
        /// </summary>
        public int PlayOrder { get; set; }

        /// <summary>
        /// Loads the specified nav node.
        /// </summary>
        /// <param name="navNode">The nav node.</param>
        /// <returns></returns>
        internal static NavPoint Load(XElement navNode)
        {
            NavPoint nav = new NavPoint();
            nav.ID = navNode.Attribute("id").Value;
            nav.PlayOrder = int.Parse(navNode.Attribute("playOrder").Value);
            nav.Label = navNode.Elements().First(e => e.Name.LocalName == "navLabel").Elements().First(e => e.Name.LocalName == "text").Value;
            nav.SrcID = navNode.Elements().First(e => e.Name.LocalName == "content").Attributes().First(e => e.Name.LocalName == "src").Value;
            return nav;
        }

        /// <summary>
        /// Saves the specified navP.
        /// </summary>
        /// <param name="navP">The navP.</param>
        /// <returns></returns>
        internal static XElement Save(NavPoint navP)
        {
            XElement xNav = new XElement("navPoint");
            xNav.Add(new XAttribute("id", navP.ID));
            xNav.Add(new XAttribute("playOrder", navP.PlayOrder));

            XElement label = new XElement("navLabel");
            label.Add(navP.Label);
            xNav.Add(label);

            XElement content = new XElement("content");
            content.Add(new XAttribute("src", navP.SrcID));
            xNav.Add(content);

            return xNav;
        }
    }
}